import ika
import math

def RotatePoint(x, y, angle):
    r = math.hypot(x, y)
    theta = math.atan(float(y) / float(x))
    if x < 0:
        theta += math.pi

    theta += angle
    x = r * math.cos(theta)
    y = r * math.sin(theta)
    return x, y

def RotateBlit(img, cx, cy, angle, scale = 1.0, blendmode = ika.AlphaBlend):
    halfx = img.width / 2
    halfy = img.height / 2
    # TODO: use a matrix to make this more efficient.
    p1 = RotatePoint(-halfx, -halfy, angle)
    p2 = RotatePoint(halfx, -halfy, angle)
    p3 = RotatePoint(halfx, halfy, angle)
    p4 = RotatePoint(-halfx, halfy, angle)

    p1 = (p1[0] * scale) + cx, (p1[1] * scale) + cy
    p2 = (p2[0] * scale) + cx, (p2[1] * scale) + cy
    p3 = (p3[0] * scale) + cx, (p3[1] * scale) + cy
    p4 = (p4[0] * scale) + cx, (p4[1] * scale) + cy

    ika.Video.DistortBlit(img, p1, p2, p3, p4, blendmode)